package com.zemb.flxwear.Utils;

import static com.clj.fastble.utils.HexUtil.charToByte;

public class ByteUtils {

    /**
     * 字节数组转16进制
     *
     * @param bytes 需要转换的byte数组
     * @return 转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
//            sb.append(hex);
            sb.append(hex + " ");
        }
        return sb.toString();
    }

    /**
     * 16进制转字节数组
     *
     * @param hexString 需要转换的Hex字符串
     * @return 转换后的byte数组
     */
    public static byte[] hexToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.replace(" ", "");
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
   //字节数组转int
    public static int bytesToTen(String high, String low) {
        int raw = Integer.parseInt(high,16) * 256 + Integer.parseInt(low,16);
        if (raw >= 32768) {

            return raw - 65536;
        }
        return raw;
    }

    //16位高低数据转化为int
    public static int hexToInt(byte high, byte low) {
        int raw = Integer.parseInt( Integer.toHexString(high & 0xFF),16) * 256 + Integer.parseInt( Integer.toHexString(low & 0xFF),16);
        if (raw >= 32768) {
            return raw - 65536;
        }

        return raw;
    }

}
